package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TableLayout;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.ExpenseMasterAdapter;
import biznussoft.fieldservice360.listeners.DialogListener;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.ExpensesModel;
import biznussoft.fieldservice360.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ExpensesMasterFragment extends BaseFragment implements OnItemClickListener, OnClickListener{
	private GlobalListener mListener;
	private ListView lv;
	public static  ArrayList<ExpensesModel> expenseList;
	private RestClient client;
	private Dialog progressDialog ;
	private Spinner spType;
	private TableLayout viewMode;
	private LinearLayout editMode;
	private Button save;
	private EditText etAmount,etDescription,etTransactionDate;
	private DialogListener listener;
	private CheckBox mBillable;
	private String mId;
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mListener = (GlobalListener) getActivity();
		listener = (DialogListener) getActivity();
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.expensemaster, null);
	}
	
	              
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.expenseListview);
		lv.setOnItemClickListener(this);
		spType = (Spinner) getView().findViewById(R.id.spExpenseType);
		viewMode = (TableLayout) getView().findViewById(R.id.ttLayout);
		editMode = (LinearLayout) getView().findViewById(R.id.lllayoutexpense_new_mode);
		save = (Button) getView().findViewById(R.id.save);
		etAmount = (EditText)getView().findViewById(R.id.etAmount);
		etDescription = (EditText)getView().findViewById(R.id.etDescription);
		etTransactionDate = (EditText) getView().findViewById(R.id.ettransactionDate);
		mBillable = (CheckBox) getView().findViewById(R.id.cbeditBillable);
		
		etTransactionDate.setOnClickListener(this);
		save.setOnClickListener(this);
		client =  HomeActivity.mActivity.client;
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		MenuItem addAccount = menu.add("Expense");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		addAccount.setIcon(R.drawable.add); 
		
		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		
		if(item.getTitle().equals("Expense")){
			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
		}
		
		return super.onOptionsItemSelected(item);
	}

	
	public void getExpenses(String id){           

		try{
			mId = id;
			progressDialog = biznussoft.fieldservice360.utils.ProgressDialog.getInstance().createProgressDialog(getActivity());
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();
			String serviceOrder = "SELECT  Name,Id,Activity_Name__c,FConnect__Technician__c,FConnect__Expense_Type__c,FConnect__Amount__c,FConnect__Billable__c,FConnect__Discription__c,FConnect__Technician_Date__c,FConnect__Activity__c From FConnect__Expense__c where FConnect__Activity__c ="+"'"+id+"'";

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {            
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						expenseList = new ArrayList<ExpensesModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ExpensesModel bean = _gson.fromJson(jsonArray.getString(i), ExpensesModel.class);
								expenseList.add(bean);
							}
						}

						showRecords();

					} catch (Exception e) {

						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
	}

	private void showRecords(){
		progressDialog.dismiss();
		ExpenseMasterAdapter adapter = new ExpenseMasterAdapter(getActivity(),expenseList);
		lv.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		mListener.displayFields(position, "ExpenseMaster");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.save:
			newTime();
			break;
		case R.id.ettransactionDate:
			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = false;
			Session.sTime = false;
			Session.sExpense = false;
			Session.sNewTime = false;
			Session.sNewExpenses = true;
			listener.nextDialog("date");
		default:
			break;
		}
	}
	
	private void newTime(){                      

		
		boolean flag = mBillable.isChecked();
		
		String objectType = "FConnect__Expense__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Activity__c",mId);                  
		fields.put("FConnect__Technician__c",Session.sID);
		fields.put("FConnect__Expense_Type__c",spType.getSelectedItem().toString());
		fields.put("FConnect__Amount__c",etAmount.getText().toString());  
		fields.put("FConnect__Discription__c", etDescription.getText().toString());
		fields.put("FConnect__Billable__c",flag);
		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(Bean_Class.api_Version,objectType,fields);


			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						finishFragment();
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}


	}
	
	public void setTransactionDate(String date){

		etTransactionDate.setText(date);
	}
	public void finishFragment(){
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}

}
